import 'package:common/network/http/api_server.dart';
import 'package:common/network/http/http.dart';
import 'package:common/router.dart';
import 'package:common/ui/pop.dart';
import 'package:flutter/material.dart';

import '../route.dart';

class Login extends StatefulWidget {
  @override
  LoginState createState() => LoginState();
}

class LoginState extends State<Login> with WidgetsBindingObserver {
//  监听容器 （如Activity） 的生命周期
  AppLifecycleState? _lastLifecycleState;

  late _Controller controller;

  get _inputWidgets => Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            child: TextField(
              controller: controller.phone,
              onChanged: (value) => setState(() {
                controller.enableLoginBtn();
              }),
            ),
            margin: const EdgeInsets.all(20),
          ),
          Container(
            child: controller.isLogin
                ? TextField(
                    decoration: InputDecoration(hintText: '请输入6-18位密码'),
                    controller: controller.pw,
                    onChanged: (value) => setState(() {
                      controller.enableLoginBtn();
                    }),
                  )
                : Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                        Expanded(
                          child: TextField(
                            decoration: InputDecoration(
                              hintText: '请输入6位验证码',
                            ),
                            controller: controller.captcha,
                            onChanged: (value) => setState(() {
                              controller.enableLoginBtn();
                            }),
                          ),
                        ),
                        MaterialButton(
                          child: Text(
                            "获取验证码",
                          ),
                          padding: EdgeInsets.symmetric(
                              vertical: 15, horizontal: 30),
                          onPressed: controller.phone.value.text.isEmpty ||
                                  controller.loading
                              ? null
                              : () async {
                                  setState(() {
                                    controller.loading = true;
                                  });
                                  await controller._gCaptcha();

                                  controller.loading = false;
                                  setState(() {});
                                },
                        ),
                      ]),
            margin: const EdgeInsets.all(20),
          ),
        ],
      );

  get _2loginOrRegister => Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextButton(
            onPressed: () => setState(() => controller._2login()),
            child: Text(
              "登录",
              style: _TextStyleLogin,
            ),
          ),
          TextButton(
              onPressed: () => setState(() => controller._2register()),
              child: Text(
                "注册",
                style: _TextStyleRegister,
              )),
        ],
      );

  get _TextStyleLogin => TextStyle(
      color: controller.isLogin ? Colors.green : Colors.redAccent,
      backgroundColor: controller.isLogin ? Colors.redAccent : Colors.green);

  get _TextStyleRegister => TextStyle(
      color: controller.isLogin ? Colors.redAccent : Colors.green,
      backgroundColor: controller.isLogin ? Colors.green : Colors.redAccent);

  get onPressed => {
        !controller.enable2Login || controller.loading
            ? null
            : () async {
                PopHeler.show();
                setState(() {
                  controller.loading = true;
                });
                if (controller.isLogin) {
                  await controller._login();
                } else {
                  await controller._register();
                }
                if (mounted) {
                  setState(() {
                    controller.loading = false;
                  });
                  PopHeler.dismiss();
                }
              }
      };

  @override
  void initState() {
    controller = _Controller();
    super.initState();
    WidgetsBinding.instance?.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    _lastLifecycleState = state;
    // setState(() {});
    debugPrint(_lastLifecycleState.toString());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      /*appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(title),
      ),*/
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _2loginOrRegister,
            _inputWidgets,
            MaterialButton(
              padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 60),
              child: const Text('登录'),
              onPressed: onPressed,
            ),
          ],
        ),
      ),
    );
  }
}

class _Controller {
  var phone = TextEditingController();
  var enable2Login = false;

  bool isLogin = true;

  var pw = TextEditingController();

  var captcha = TextEditingController();

  bool loading = false;

  _2login() {
    isLogin = true;
    enableLoginBtn();
  }

  _2register() {
    open(RouteConfig.featureSome, arguments: {'msg': ' 上个页面传递过来的数据'});
    isLogin = false;
    enableLoginBtn();
  }

  enableLoginBtn() {
    enable2Login = !(phone.value.text.isEmpty ||
        (isLogin ? pw.value.text.isEmpty : captcha.value.text.isEmpty));
  }

  Future<void> _gCaptcha() async {
    final Map<String, dynamic> params = {
      'Phone': phone.value.text,
      'smsType': 6,
      'AppTagID': 7,
    };
    var map = await HostHttp.instance.sign(params);

    var ma = await HTTPUtil.instance
        .req('api/UserBase/UserBase_SendSms', queryParameters: map.cast());
  }

  _register() async {
    final Map<String, dynamic> params = {
      'Phone': phone.value.text,
      'Code': captcha.value.text,
      'AppTagID': "7",
    };
    var map = await HostHttp.instance.sign(params);

    var ma = await HTTPUtil.instance
        .req('api/UserBase/UserBase_QuickLogin', queryParameters: map.cast());
  }

  _login() async {
    final Map<String, dynamic> params = {
      'UserAccount': phone.value.text,
      'UserPwd': pw.value.text,
      'AppTagID': 7,
    };
    var map = await HostHttp.instance.sign(params);

    await HTTPUtil.instance.req(
      'api/PrimarySchool/SuperApp_Login',
      queryParameters: map.cast(),
      onSuccess: (data) {
        PopHeler.toast(SomeRootEntityBody.fromJson(data).toString());
      },
      onFail: ({code, msg}) {
        PopHeler.toast(code.toString() + ':' + (msg ?? ''));
      },
    );

    /* var list = (res.data as List).map((e) {
    return NetListBean().fromJson(e);
  }).toList();*/
  }
}

///
/// Code generated by jsonToDartModel https://ashamp.github.io/jsonToDartModel/
///

const String jsonKeySomeRootEntityBodyUserName = "UserName";
const String jsonKeySomeRootEntityBodyUserPic = "UserPic";
const String jsonKeySomeRootEntityBodyUserToken = "UserToken";
const String jsonKeySomeRootEntityBodyLoginNum = "LoginNum";
const String jsonKeySomeRootEntityBodyIsVip = "isVip";
const String jsonKeySomeRootEntityBodyIsFillUserInfo = "IsFillUserInfo";
const String jsonKeySomeRootEntityBodyUserType = "UserType";
const String jsonKeySomeRootEntityBodySuperAppFLAG = "SuperAppFLAG";

class SomeRootEntityBody {
/*
{
  "UserName": "就举报",
  "UserPic": "/uploads/face/official/180x180/20201125/7446a21b-05f4-4ded-a15c-29a1a0c6c34e.png",
  "UserToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVSUQiOiI0NDkwMzMiLCJBUFBUQUdJRCI6IjciLCJBUFBVSUQiOiIyNDc0NDciLCJBUFBTWVNURU1UWVBFIjoiMCIsIkd1aWQiOiIwIiwiZXhwIjoxNjIyMzg5NTA2LCJpc3MiOiJpZXMuYWNhZHNvYy5jb20uY24iLCJhdWQiOiJpZXMuYWNhZHNvYy5jb20uY24ifQ.YMyGSLd5LqOopxs1bM2sU9IOXvtvviHPKG_hqNbt80Y",
  "LoginNum": 13,
  "isVip": 2,
  "IsFillUserInfo": 0,
  "UserType": 0,
  "SuperAppFLAG": "0"
}
*/

  String? UserName;
  String? UserPic;
  String? UserToken;
  int? LoginNum;
  int? isVip;
  int? IsFillUserInfo;
  int? UserType;
  String? SuperAppFLAG;

  @override
  String toString() {
    return 'SomeRootEntityBody{UserName: $UserName, UserPic: $UserPic, UserToken: $UserToken, LoginNum: $LoginNum, isVip: $isVip, IsFillUserInfo: $IsFillUserInfo, UserType: $UserType, SuperAppFLAG: $SuperAppFLAG}';
  }

  SomeRootEntityBody({
    this.UserName,
    this.UserPic,
    this.UserToken,
    this.LoginNum,
    this.isVip,
    this.IsFillUserInfo,
    this.UserType,
    this.SuperAppFLAG,
  });

  static SomeRootEntityBody? fromJson(Map<String, dynamic?>? json) =>
      json == null
          ? null
          : SomeRootEntityBody(
              UserName: json[jsonKeySomeRootEntityBodyUserName]?.toString(),
              UserPic: json[jsonKeySomeRootEntityBodyUserPic]?.toString(),
              UserToken: json[jsonKeySomeRootEntityBodyUserToken]?.toString(),
              LoginNum: json[jsonKeySomeRootEntityBodyLoginNum]?.toInt(),
              isVip: json[jsonKeySomeRootEntityBodyIsVip]?.toInt(),
              IsFillUserInfo:
                  json[jsonKeySomeRootEntityBodyIsFillUserInfo]?.toInt(),
              UserType: json[jsonKeySomeRootEntityBodyUserType]?.toInt(),
              SuperAppFLAG:
                  json[jsonKeySomeRootEntityBodySuperAppFLAG]?.toString());

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data[jsonKeySomeRootEntityBodyUserName] = UserName;
    data[jsonKeySomeRootEntityBodyUserPic] = UserPic;
    data[jsonKeySomeRootEntityBodyUserToken] = UserToken;
    data[jsonKeySomeRootEntityBodyLoginNum] = LoginNum;
    data[jsonKeySomeRootEntityBodyIsVip] = isVip;
    data[jsonKeySomeRootEntityBodyIsFillUserInfo] = IsFillUserInfo;
    data[jsonKeySomeRootEntityBodyUserType] = UserType;
    data[jsonKeySomeRootEntityBodySuperAppFLAG] = SuperAppFLAG;
    return data;
  }
}
